package reduce.fz.com.reduce.fragment;


import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;
import com.example.qingshengzheng.material.Text;

import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.activity.UserDetailActivity;
import reduce.fz.com.reduce.activity.VideoCardDetailActivity;
import reduce.fz.com.reduce.adapter.BaseRecycleViewHolder;
import reduce.fz.com.reduce.adapter.CardLikeUserListAdapter;
import reduce.fz.com.reduce.bean.PkGroup;
import reduce.fz.com.reduce.bean.ServiceException;
import reduce.fz.com.reduce.bean.User;
import reduce.fz.com.reduce.bean.VideoCard;
import reduce.fz.com.reduce.bean.page.Pagination;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.custom.FollowView;
import reduce.fz.com.reduce.custom.HorizontalLinearLayoutManager;
import reduce.fz.com.reduce.custom.NetworkImageView;
import reduce.fz.com.reduce.custom.view.RoundNetworkImageView;
import reduce.fz.com.reduce.event.ShowPubVideoEvent;
import reduce.fz.com.reduce.fragment.base.BaseListFragment;
import reduce.fz.com.reduce.fragment.base.BaseListHeaderFragment;
import reduce.fz.com.reduce.service.PkService;
import reduce.fz.com.reduce.service.VideoService;
import reduce.fz.com.reduce.service.preference.UserPreference;
import reduce.fz.com.reduce.util.ApiUtil;
import reduce.fz.com.reduce.util.DateUtil;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.ScreenUtils;
import reduce.fz.com.reduce.util.ServiceBuilder;
import reduce.fz.com.reduce.util.ToastUtil;
import reduce.fz.com.reduce.util.VitamioOper;

public class PkVideoListFragment extends BaseListHeaderFragment<BaseRecycleViewHolder, VideoCard, PkGroup> {

    //更多弹出框
    private PopupWindow reportWindow;
    private VideoService videoService = ServiceBuilder.builderVideoService(null);
    private PkService pkService = ServiceBuilder.builderPkService(null);
    //PK小组
    private PkGroup pkGroup;

    //创建fragment
    public static PkVideoListFragment create(PkGroup pkGroup) {
        PkVideoListFragment fragment = new PkVideoListFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("pkgroup", pkGroup);
        fragment.setArguments(bundle);
        return fragment;
    }


    //显示更多窗口
    public void showReportWindow(final VideoCard card) {
        View view = layoutInflater.inflate(R.layout.view_report, null);
        reportWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        reportWindow.setTouchable(true);
        reportWindow.setOutsideTouchable(true);
        TextView mReport = (TextView) view.findViewById(R.id.tv_report);
        TextView mcancel = (TextView) view.findViewById(R.id.tv_cancel);
        reportWindow.setBackgroundDrawable(new BitmapDrawable());
        reportWindow.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        mReport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                videoService.report(card.cardid, new AbResponseListener<HashMap>(new TypeReference<Result<HashMap>>() {
                }) {
                    @Override
                    public void error(ServiceException e) {
                        reportWindow.dismiss();

                    }

                    @Override
                    public void responseInfo(Result<HashMap> data) {
                        ToastUtil.showMessage("举报成功!");
                        reportWindow.dismiss();

                    }
                });
                reportWindow.dismiss();
            }
        });
        mcancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reportWindow.dismiss();
            }
        });
    }

    /**
     * header区域
     *
     * @param parent
     * @return
     */
    @Override
    protected BaseRecycleViewHolder createHeaderViewHolder(ViewGroup parent) {
        View view = layoutInflater.inflate(R.layout.view_pk_video_header, parent, false);
        return new VideoCardHeaderViewHolder(view);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        //获取pkGroup
        pkGroup = (PkGroup) getArguments().getSerializable("pkgroup");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEvent(ShowPubVideoEvent event) {
        if (((long) event.card.pid) == ((long) pkGroup.pid)) {
            addFrist(event.card);
        }
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        addHeader(pkGroup);
    }

    public PkVideoListFragment() {
    }


    public void forwardDetail(User user) {
        Intent intent = new Intent(getActivity(), UserDetailActivity.class);
        intent.putExtra("uid", user.uid);
        startActivity(intent);

    }

    @Override
    public LinearLayoutManager getLayoutManager() {
        return null;
    }

    @Override
    protected BaseRecycleViewHolder createItemViewHolder(ViewGroup parent) {
        View view = layoutInflater.inflate(R.layout.view_pk_video_item, parent, false);
        return new VideCardViewHolder(view, new VideoMoreListener() {
            @Override
            public void clickReport(VideoCard card) {
                //更多操作
                showReportWindow(card);
            }

            @Override
            public void clickUser(User user) {
                //跳转到用户详情
                forwardDetail(user);
            }

            @Override
            public void clickZan(VideoCard card) {
                videoService.praise(card.cardid, card.videoAttach.ispraise, new AbResponseListener<HashMap>(new TypeReference<Result<HashMap>>() {
                }) {
                    @Override
                    public void error(ServiceException e) {
                    }

                    @Override
                    public void responseInfo(Result<HashMap> data) {
                    }
                });
            }

            @Override
            public void clickComment(VideoCard card) {
                forwardCardDetail(card);

            }
        }, getActivity());
    }

    public void forwardCardDetail(VideoCard videocard) {
        Intent intent = new Intent(getActivity(), VideoCardDetailActivity.class);
        intent.putExtra("cardid", videocard.cardid);
        startActivity(intent);


    }

    @Override
    public void request(String url) {
        HttpUtils.get(url, new AbResponseListener<List<VideoCard>>(new TypeReference<Result<List<VideoCard>>>() {
        }) {
            @Override
            public void error(ServiceException e) {
                loadingDialog.dismiss();

            }

            @Override
            public void responseInfo(Result<List<VideoCard>> data) {
                addResult(data);
            }
        });
    }


    @Override
    protected BaseRecycleViewHolder createfootViewHolder(View view) {
        return new BaseRecycleViewHolder(view) {
            @Override
            public void renderView(Object data, int position) {

            }
        };
    }

    @Override
    protected String setUrlBeforeRequest(List<VideoCard> datas, Pagination pagination) {
        String url = ApiUtil.getApi(context, R.array.api_pk_video_list, pkGroup.pid, pagination.getPageNo(), pagination.getPageSize());
        return url;
    }

    @Override
    protected int getPageType() {
        return 0;
    }

    public interface VideoMoreListener {
        public void clickReport(VideoCard card);

        public void clickUser(User user);

        public void clickZan(VideoCard card);

        public void clickComment(VideoCard card);
    }

    /**
     * header部分
     */
    public static class VideoCardHeaderViewHolder extends BaseRecycleViewHolder<PkGroup> {
        //pk小组描述
        private TextView mDesc;
        //pk昵称
        private TextView mNickName;
        //用户头像
        private RoundNetworkImageView mUseravatar;

        /**
         * 初始化
         *
         * @param itemView
         */
        public VideoCardHeaderViewHolder(View itemView) {
            super(itemView);
            mDesc = (TextView) itemView.findViewById(R.id.tv_desc);
            mNickName = (TextView) itemView.findViewById(R.id.tv_user_nickname);
            mUseravatar = (RoundNetworkImageView) itemView.findViewById(R.id.iv_user_avatar);
        }

        @Override
        public void renderView(PkGroup data, int position) {
            mDesc.setText(data.description);
            mNickName.setText(data.user.nickname);
            mUseravatar.setImageUrl(data.user.avatar, HttpUtils.getAvatarImageLoader());

        }
    }


    public static class VideCardViewHolder extends BaseRecycleViewHolder<VideoCard> implements View.OnClickListener {
        //视频区域
        private SurfaceView mVideo;
        //视频描述
        private TextView mVideoDesc;
        private TextView mPubTime;
        private TextView mComment;
        //赞
        private TextView mZan;
        //分享
        private TextView mfenxiang;
        //更多
        private TextView mMore;
        //关注
        private FollowView mFollow;
        private RoundNetworkImageView mUserAvatar;
        private TextView mNickName;
        private NetworkImageView mThum;
        private RecyclerView card_like_user_list;

        //
        private RelativeLayout mSurfaceLayout;
        private Activity mActivity;
        private VitamioOper vitamioOper;
        private VideoCard card;
        private VideoMoreListener listener;
        private CardLikeUserListAdapter likeAdapter;
        private ProgressBar video_progressbar;
        private ProgressBar cache_progressbar;
        private ImageView mPlay;


        public VideCardViewHolder(View itemView, VideoMoreListener listener, Activity mActivity) {
            super(itemView);
            this.listener = listener;
            this.mActivity = mActivity;
            mPlay = (ImageView) itemView.findViewById(R.id.iv_play);
            mThum = (NetworkImageView) itemView.findViewById(R.id.iv_video_thum);
            mComment = (TextView) itemView.findViewById(R.id.tv_comment);
            mSurfaceLayout = (RelativeLayout) itemView.findViewById(R.id.surface_contaier);
            video_progressbar = (ProgressBar) itemView.findViewById(R.id.video_progressbar);
            cache_progressbar = (ProgressBar) itemView.findViewById(R.id.cache_progressbar);
            mFollow = (FollowView) itemView.findViewById(R.id.fv_follow);
            mUserAvatar = (RoundNetworkImageView) itemView.findViewById(R.id.iv_user_avatar);
            mNickName = (TextView) itemView.findViewById(R.id.tv_user_nickname);
            mVideo = (SurfaceView) itemView.findViewById(R.id.sv_video);
            mPubTime = (TextView) itemView.findViewById(R.id.tv_pub_time);
            resizeSurface();
            mVideoDesc = (TextView) itemView.findViewById(R.id.tv_video_desc);
            mfenxiang = (TextView) itemView.findViewById(R.id.tv_fenxiang);
            card_like_user_list = (RecyclerView) itemView.findViewById(R.id.card_like_user_list);
            mMore = (TextView) itemView.findViewById(R.id.tv_more);
            mZan = (TextView) itemView.findViewById(R.id.tv_zan);
            initLike();
            vitamioOper = VitamioOper.instance(mActivity, mVideo);
            vitamioOper.setProgressBar(video_progressbar);
            vitamioOper.setBufferdBar(cache_progressbar);
            vitamioOper.setVideoThum(mThum);
            vitamioOper.setPlayBtn(mPlay);
            mSurfaceLayout.setOnClickListener(this);
            mfenxiang.setOnClickListener(this);
            mPlay.setOnClickListener(this);
            mMore.setOnClickListener(this);
            mZan.setOnClickListener(this);
            mComment.setOnClickListener(this);
            mFollow.setOnClickListener(this);
        }

        /**
         * 重置视频播放尺寸
         */
        public void resizeSurface() {
            int width = ScreenUtils.getScreenW();
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(width, width);
            mSurfaceLayout.setLayoutParams(lp);
        }


        public void initLike() {
            HorizontalLinearLayoutManager hm = new HorizontalLinearLayoutManager(itemView.getContext());
            card_like_user_list.setLayoutManager(hm);
            // 设置ItemAnimator
            card_like_user_list.setItemAnimator(new DefaultItemAnimator());
            // 设置固定大小
            card_like_user_list.setHasFixedSize(true);
            likeAdapter = new CardLikeUserListAdapter(itemView.getContext(), new CardLikeUserListAdapter.OnClickUserAvatarListener() {
                @Override
                public void onClickUser(User user) {
                    if (user != null)
                        listener.clickUser(user);
                }
            });
            card_like_user_list.setAdapter(likeAdapter);
        }

        public void setPraiseUsers(List<User> users) {
            if (likeAdapter != null)
                likeAdapter.replaceLikeUsers(users);
        }


        @Override

        public void renderView(VideoCard data, int position) {
            this.card = data;
            mThum.setImageUrl(data.video.thumUrl, HttpUtils.getImageLoader());
            vitamioOper.setUrl(data.video.url);
            mZan.setText("  " + data.videoAttach.praisenum);
            if (data.videoAttach.ispraise)
                mZan.setSelected(true);
            else
                mZan.setSelected(false);
            User me = UserPreference.getUser();
            mComment.setText(" " + data.videoAttach.replynum);
            mPubTime.setText(DateUtil.getInterval(data.pubtime));
            mFollow.setStatus(me.uid, data.user);
            mUserAvatar.setImageUrl(data.user.avatar, HttpUtils.getAvatarImageLoader());
            mNickName.setText(data.user.nickname);
            mVideoDesc.setText(data.description);

        }


        /**
         * 点赞
         */
        public void zan(VideoCard card) {
            if (!card.videoAttach.ispraise)
                praise(card);
            else {
                dispraise(card);
            }


        }

        /**
         * 点赞
         */
        public void praise(VideoCard card) {
            card.videoAttach.ispraise = true;
            card.videoAttach.praisenum++;
            listener.clickZan(card);
            mZan.setSelected(true);
            mZan.setText("  " + card.videoAttach.praisenum);
            likeAdapter.prependUser(UserPreference.getUser());

        }

        /**
         * 取消点赞
         */
        public void dispraise(VideoCard card) {
            card.videoAttach.ispraise = false;
            card.videoAttach.praisenum--;
            listener.clickZan(card);
            mZan.setText("  " + card.videoAttach.praisenum);
            mZan.setSelected(false);
            likeAdapter.removeUser(UserPreference.getUser());


        }


        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.surface_contaier:
                    vitamioOper.play();
                    break;
                case R.id.tv_comment:
                    listener.clickComment(card);
                    break;
                case R.id.iv_play:
                    vitamioOper.play();
                    break;
                case R.id.tv_more:
                    listener.clickReport(card);
                    break;
                case R.id.tv_fenxiang:
                    ToastUtil.showMessage("该功能暂时不支持!");
                    break;
                case R.id.tv_zan:
                    zan(card);
                    break;
                case R.id.fv_follow:
                    mFollow.doToggleAction();
                default:
                    break;
            }

        }
    }
}